<?php

namespace App\Http\Controllers\admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;
class ListController extends Controller
{
    //
    public function index(Request $request)
    {
    	//保存搜索条件
    	$where = [];
    	//实例化要操作的表
    	$db = DB::table("users");
    	//判断有没有要搜索name字段的值
    	if($request->has("name")){
            //获取要搜索的name字段的值
            $name = $request->input("name");
            //添加where模糊查询匹配条件
    		$db->where("name","like","%{$name}%");
    		$where['name'] = $name;
    	}
    	//分页
    	$list = $db->paginate(5);

    	//加载模板
    	return view("admin.users.list",["list"=>$list,"where"=>$where]);
    }
    public function create()
    {
    	return view("admin.users.add");
    }
    public function store(Request $request)
    {
    	//自动规则
    	$messages = [
    		'required' =>":attribute 的字段是必要的",
   	];
   		$this->validate($request,[
   			"name" =>"required|unique:users|max:16",
   			],$messages);
   		$data = $request->except("_token");
        $data['password']=md5($request->input('password'));
        if (session()->get('adminuser')->level==0) {
            $id = DB::table("users")->insertGetId($data);
            if($id>0){
                return redirect("admin/list");
            }
        }else{
            return back()->with('msg','您无此权限');
        }
    }

    public function destroy($id)
    {
        $row=DB::table("users")->where("id",$id)->delete();
        if($row>0){
            return redirect('admin/list');
        }
    }
    public function edit($id)
    {
    	$user = DB::table("users")->where("id",$id)->first();

    	return view("admin.users.edit",["user"=>$user]);
    }
    public function update($id,Request $request)
    {

    	$data = $request->only("name","level");
    	$row = DB::table("users")->where("id",$id)->update($data);
    	if($row>0){
    		return redirect('admin/list');

    	}
    }
}
